package cn.asiontang.utils;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Debug;
import android.text.format.Formatter;

public class MemoryUtils
{
    private static Application mContext;

    public static ActivityManager.MemoryInfo displayBriefMemory()
    {
        final ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        getActivityManager().getMemoryInfo(info);

        //        LogEx.w(TAG, "系统剩余内存:" + Formatter.formatFileSize(mContext, info.availMem));
        //        LogEx.w(TAG, "系统是否处于低内存运行：" + info.lowMemory);
        //        LogEx.w(TAG, "当系统剩余内存低于" + Formatter.formatFileSize(mContext, info.threshold) + "时就看成低内存运行");
        //        LogEx.w(TAG, "应用最大使用内存:" + Formatter.formatFileSize(mContext, Runtime.getRuntime().maxMemory()));
        //        LogEx.w(TAG, "应用已用内存:" + getAppUseMemory());
        //        LogEx.w(TAG, "应用剩余内存:" + Formatter.formatFileSize(mContext, Runtime.getRuntime().freeMemory()));

        return info;
    }

    private static ActivityManager getActivityManager()
    {
        return (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    }

    /**
     * @return 应用已用内存 kb
     */
    public static String getAppUseMemory()
    {
        final Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
        Debug.getMemoryInfo(memoryInfo);
        return memoryInfo.dalvikPrivateDirty + memoryInfo.getTotalSharedDirty() + memoryInfo.getTotalPrivateDirty() + "KB";
    }

    /**
     * @return 系统剩余内存
     */
    public static String getAvailMem()
    {
        return Formatter.formatFileSize(mContext, displayBriefMemory().availMem);
    }

    /**
     * @return 应用剩余内存
     */
    public static String getFreeMemory()
    {
        return Formatter.formatFileSize(mContext, Runtime.getRuntime().freeMemory());
    }

    /**
     * @return 低内存运行临界值
     */
    public static String getLowMemoryRunThreshold()
    {
        return Formatter.formatFileSize(mContext, displayBriefMemory().threshold);
    }

    /**
     * @return 应用最大使用内存
     */
    public static String getMaxMemory()
    {
        return Formatter.formatFileSize(mContext, Runtime.getRuntime().maxMemory());
    }

    /**
     * 一般在自定义Application中的onCreate里初始化<br/>
     * 【不能在Application的构造函数里调用！】<br/>
     * 因为此时应用的String资源尚未初始化完毕，会报Null异常！
     */
    public static void init(final Application app)
    {
        mContext = app;
    }

    /**
     * @return 系统是否处于低内存运行
     */
    public static boolean isInLowMemory()
    {
        return displayBriefMemory().lowMemory;
    }
}
